package com.nft.utils.string;

import com.nft.utils.common.IJsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 类描述：常用函数
 * 
 * 其他常用工具类：org.apache.commons.lang3.StringUtils
 * 
 * @author 
 *
 */
public class StringUtil {
	private static final Logger logger = LoggerFactory.getLogger(StringUtil.class);
	
	public static boolean isEmpty(Object str) {
		return (str == null || "".equals(str));
	}
	
	public static boolean isNotEmpty(Object str) {
		return !isEmpty(str);
	}
	
	/**
	 * 判断是否为空
	 *   
	 * @param str
	 * @return
	 */
	public static boolean isBlank(String str) {
		return StringUtils.isBlank(str);
	}
	
	/**
	 * Object 转 String
	 * 
	 * @param src
	 * @return
	 */
	public static String nullToString(Object src) {
		if (src == null)
			return "";
		else
			return src.toString();
	}

	/**
	 * @param str 需要判断的数据
	 * @param value 为空返回的数据
	 * @description 若为空，则返回value
	 * @author Lipf
	 * @create 2018-01-09 15:28:53
	 */
	public static String nullToValue(Object str, Object value) {
		if (isEmpty(str)) {
			return nullToString(value);
		}
		return str.toString();
	}

	/**
	 * Object 转 String
	 * 
	 * @param src
	 * @return
	 */
	public static String zeroToString(Object src) {
		if (src == null)
			return "0";
		else
			return src.toString();
	}

	public static String zeroForString(Object src) {
		if (src == null || "".equals(src))
			return "0";
		else
			return src.toString();
	}

	/**
	 * Object 转 String
	 * 
	 * @param src
	 * @return
	 */
	public static String nullForString(Object src) {
		if (src == null)
			return null;
		else
			return src.toString();
	}

	public static int digestForString(Object src) {
		if (src == null)
			return 0;
		else
			return ((Double)Double.parseDouble(src.toString())).intValue();
	}

	/**
	 * Map<String, String> 转 Map<String, Object>
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, Object> turnToMapObject(Map<String, String> map) {
		Map<String, Object> retMap = new HashMap<>();
		for (Object k : map.keySet()) {
			retMap.put(k.toString(), map.get(k));
		}
		return retMap;
	}

	/**
	 * 如果为null则转为""
	 * @param str
	 * @return
	 */
	public static String nullHandeler(String str){
		str = str == null?"":str;
		return str;
	}

	/**
	 * 校验Map<String, Object>，Object对象如果为null则转为String
	 * @param map map
	 * @return map
	 */
	public static Map<String, Object> mapNullToString(Map<String, Object> map) {
		Map<String, Object> ret = new HashMap<>();

		for (Object k : map.keySet()) {
			ret.put(k.toString(), map.get(k)==null?"":map.get(k));
		}
		
		return ret;
	}
	
	/**
	 * 保留小数点i位
	 * @param ob
	 * @param i
	 * @return
	 */
	public static String reservePoint(Object ob, int i) {
		BigDecimal _ob = new BigDecimal(0);
		
		if (ob instanceof String && !"".equals(ob))
			_ob = new BigDecimal((String)ob);
		if (ob instanceof Integer)
			_ob = new BigDecimal((int)ob);
		if (ob instanceof Double)
			_ob = new BigDecimal((double)ob);
		if (ob instanceof Long)
			_ob = new BigDecimal((long)ob);
		
		BigDecimal f1 = _ob.setScale(i, BigDecimal.ROUND_HALF_UP);
		return f1.toString();
	}
	
	/**
	 * 数据集 null 转为 ""
	 * @param obj
	 * @return
	 */
	public static Object notNull(Object obj){
		if(obj==null)
			obj = "";
		else if (obj instanceof Map) {
			for (Object k : ((Map)obj).keySet()) {
				Object kvalue = ((Map)obj).get(k);
				((Map)obj).put(k, notNull(kvalue));
			}
		}
		else if(obj instanceof Collection){
			for(Object o:(Collection)obj)
				notNull(o);
		}
		else if(obj.getClass().isArray() && obj instanceof Object[]){
			for(Object o:(Object[])obj)
				notNull(o);
		}
		return obj;
	}

	/**
	 * @param obj
	 * @description 返回数据集 null 转为 ""  转String
	 * @author Lipf
	 * @create 2018-07-02 10:55:47
	 */
	public static Object notNullToString(Object obj){
		if(obj==null)
			obj = "";
		else if (obj instanceof Map) {
			for (Object k : ((Map)obj).keySet()) {
				Object kvalue = ((Map)obj).get(k);
				((Map)obj).put(k, notNullToString(kvalue));
			}
		}
		else if(obj instanceof Collection){
			for(Object o:(Collection)obj)
				notNullToString(o);
		}
		else if(obj.getClass().isArray() && obj instanceof Object[]){
			for(Object o:(Object[])obj)
				notNullToString(o);
		} else {
			obj = String.valueOf(obj);
		}
		return obj;
	}

	/**
	 * 数据集 null 转为 ""
	 * @param obj
	 * @return
	 */
	public static Object notMapNull(Object obj){
		if(obj==null)
			obj = "";
		else if (obj instanceof Map) {
			Object[] objs =((Map)obj).keySet().toArray();
			for(Object k : objs){
				Object kvalue = ((Map)obj).get(k);
				if(kvalue == null)
					((Map)obj).remove(k);
			}
		}
		else if(obj instanceof Collection){
			for(Object o:(Collection)obj)
				notMapNull(o);
		}
		else if(obj.getClass().isArray() && obj instanceof Object[]){
			for(Object o:(Object[])obj)
				notMapNull(o);
		}
		return obj;
	}
	
	/**
	 * 
	 * Description:  <p>对象转为字符串。null返回""</p>
	 *                                             
	 * @author       WangshuC                
	 * Create Date:   Aug 14, 2014 5:48:28 PM
	 * @version      1.0
	 *
	 * @param obj 对象
	 * @return 字符串
	 *
	 */
	public static String getString(Object obj){
		if(obj == null){
			return "";
		}
		return "" + obj.toString();
	}
	
	/**
	 * 
	 * Description:  <p>对象转为字符串。去除左右空白。null返回""</p>
	 *                                             
	 * Author       WangshuC
	 * Create Date:   Aug 14, 2014 5:48:28 PM
	 *
	 * @param obj 对象
	 * @return 字符串
	 *
	 */
	public static String getTrimString(Object obj){
		return getString(obj).trim();
	}
	
	/**
	 * 计算UTF-8字符串占用字节数
	 * @param str 字符串
	 * @return 整数
	 */
	public static int calUTF8StringBytes(String str){
		int bytesLength = 0;
		try {
			if(str != null && !"".equals(str)){
				bytesLength = str.getBytes("UTF-8").length;
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("不支持的字符编码:{}"+e.getMessage(),e);
		}
		return bytesLength;
	}

    /**
	 * 
	 * 方法说明：不为空，包括空格
	 *
	 * Author：        wenqiangL                
	 * Create Date：   2016年8月31日 下午7:01:33
	 * History:  2016年8月31日 下午7:01:33   wenqiangL   Created.
	 *
	 * @param str 对象
	 * @return 布尔值
	 *
	 */
	public static boolean isNotBlank(String str) {
		return !isBlank(str);
	}

    /**
     * 不为空，包括空格
     * @param str
     * @return
     */
    public static boolean isNotBlank(Object str) {
        return isNotEmpty(str) && isNotBlank(str.toString());
    }
	
	
	
	/**
	 * 
	 * 方法说明：去除两侧空格
	 *
	 * Author：        wenqiangL                
	 * Create Date：   2016年8月30日 上午10:41:52
	 * History:  2016年8月30日 上午10:41:52   wenqiangL   Created.
	 *
	 * @param str 对象
	 * @return 字符串
	 *
	 */
	public static String trimToEmpty(Object str) {
        return str == null ? "" : str.toString().trim();
    }
    
	/**
	 * 校验入参,如果为空则抛出异常消息
	 *
	 * Author: GUOXUYANG
	 *
	 * @param param 对象
	 * @param msg 消息体
	 * @return 字符串
	 */
	public static String checkParam(Object param, String msg) {
		if (isEmpty(param)) {
			throw new RuntimeException(msg);
		}
		return param.toString();
	}

	/**
	 * Object 转 BigDecimal, null 返回 0
	 * @param ob
	 * @return
	 */
	public static BigDecimal turnToDecimal(Object ob) {
		BigDecimal _ob = new BigDecimal(0);
		if (isEmpty(ob)) {
			return _ob;
		}
		if (ob instanceof String && !"".equals(ob)) {
			_ob = new BigDecimal((String) ob);
		} else if (ob instanceof Integer) {
			_ob = new BigDecimal((int) ob);
		} else if (ob instanceof Double) {
			_ob = new BigDecimal((double) ob);
		} else if (ob instanceof Long) {
			_ob = new BigDecimal((long) ob);
		} else if (ob instanceof BigDecimal) {
			_ob = (BigDecimal) ob;
		}
		return _ob;
	}
	/**
	 * @param obj
	 * @description 把空字符转为null返回，主要用于数据表的插入
	 * @author cailianL
	 * @create 2017-09-07 09:57:02
	 */
	public static String getEmptyStrToNull(Object obj) {
		if (isEmpty(obj)) {
			return null;
		}
		return obj.toString();
	}
	/**
	 * 判断字符串是否包含中文
	 *
	 * @author wangyun Apr 1, 2011 8:54:11 AM
	 * @param str
	 * @return
	 */
	public static boolean includeChinese(String str) {
		if (isEmpty(str)) {
			return false;
		}
		char[] charArray = str.toCharArray();
		for (int i = 0; i < charArray.length; i++) {
			if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @param jsonStr
	 * @description 将json字符串，转换为key=value&key=value的字符
	 * @author Lipf
	 * @create 2018-08-29 23:09:28
	 */
	public static String tranJsonStr2FormStr(String jsonStr) {
		Map<String, String> map = IJsonUtil.json2Obj(jsonStr, Map.class);
		List<String> arr = new ArrayList<>();
		for (String key : map.keySet()) {
			arr.add(key + "=" + map.get(key));
		}
		return StringUtils.join(arr.iterator(), "&");
	}

	/**
	 * @param url
	 * @param param
	 * @description cong rul中得到参数  字符串都会转成小写 qrcode
	 * @author TianYouPeng
	 * @create 2019-01-21 16:43:18
	 */
	public static String urlGetParam(String url,String param){
		param = param.toLowerCase();
		String resultStr = "";
		try {
            if(url.indexOf("?")!=-1){
                String[] urlArr = url.split("\\?");
                if(urlArr.length == 2){
                    String[] paramArr = urlArr[1].split("&");
                    for(int i=0;i<paramArr.length;i++){
                        int tempIndex = param.length()+1;
                        if(paramArr[i].length() > tempIndex ){
                            if((param+"=").equals(paramArr[i].substring(0,tempIndex))){
                                resultStr = paramArr[i].substring(tempIndex,paramArr[i].length());
                            }
                        }
                    }
                }else{
                    resultStr = "";
                }
            }else{
                resultStr = url;
            }
        }catch (Exception ex){
		    ex.printStackTrace();
		    return "";
        }
		return resultStr;
	}
//
//	public static void main(String[] args){
//		System.out.println(urlGetParam("https://t2.evshine.cn/base/api/v0.1/guns/qrcode?qrCode=32321300103","qrCode"));
//	}
}
